#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Author: admin@attacker.club
Date: 2023-01-11 12:33:04
LastEditTime: 2023-01-23 23:03:03
Description: 
SDK: https://cloud.tencent.com/document/sdk
pip install tencentcloud-sdk-python
'''

import json
import re
import requests
import datetime
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.dnspod.v20210323 import dnspod_client, models
import configparser

# 配置文件设置
def ddns_config(filename):
    config = configparser.ConfigParser()
    config.read(filename) 
    config.sections()
    return config

def getip(url1,url2):
    try:
        req = requests.get(url1, timeout=3)
        if req.status_code != requests.codes.ok:
            req = requests.get(url2, timeout=3)
    except Exception as e:
        print(e)

    finally:

        ipaddr = re.findall(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", req.text)
        print("查询ip网站:",req.url,ipaddr[0])
        return ipaddr[0]


def DescribeRecord(domain,subdomain):
    try:
        # 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
        # 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
        # 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
        # cred = credential.Credential("SecretId", "SecretKey")
        # 实例化一个http选项，可选的，没有特殊需求可以跳过
        httpProfile = HttpProfile()
        httpProfile.endpoint = "dnspod.tencentcloudapi.com"

        # 实例化一个client选项，可选的，没有特殊需求可以跳过
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        # 实例化要请求产品的client对象,clientProfile是可选的
        client = dnspod_client.DnspodClient(cred, "", clientProfile)

        # 实例化一个请求对象,每个接口都会对应一个request对象
        req = models.DescribeRecordListRequest()
        params = {
            "Domain": domain,
            "Subdomain": subdomain
        }
        req.from_json_string(json.dumps(params))

        # 返回的resp是一个DescribeRecordListResponse的实例，与请求对象对应
        resp = client.DescribeRecordList(req)
        # 输出json格式的字符串回包
        return resp.to_json_string()

    except TencentCloudSDKException as err:
        print(err)
        
def ModifyDynamicDNS(ipaddr,domain,params_dict):

    try:
        httpProfile = HttpProfile()
        httpProfile.endpoint = "dnspod.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = dnspod_client.DnspodClient(cred, "", clientProfile)

        req = models.ModifyDynamicDNSRequest()
        params = {
            "Domain": domain,
            "SubDomain": params_dict['Name'],
            "RecordId": params_dict['RecordId'],
            "RecordLine": "默认",
            "Value": ipaddr
        }
        req.from_json_string(json.dumps(params))
        resp = client.ModifyDynamicDNS(req)
        # print(resp.to_json_string())
        # print('%s [%s] %s  %s记录已更新 !!!' % (now,domain,params_dict['Name'],ipaddr)
        info ="{0} [{2}.{1}] 记录更新为 {3} !!! ".format(now,domain,params_dict['Name'],ipaddr)
        print(info)

    except TencentCloudSDKException as err:
        print(err)


if __name__ == "__main__":
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    cf = ddns_config('config.txt')  # 读取配置信息
    subdomain = cf['dns']['subdomain']  # 域名
    domain = '.'.join(subdomain.split('.')[-2:])
    subdomain = subdomain.split('.')[0]
    # 获取外网ip
    url1 = cf['Query']['url1']
    url2 = cf['Query']['url2']
    ip = getip(url1,url2)
    AK = cf['AccessKey']  # AK秘钥
    cred = credential.Credential( AK['secret_id'],  AK['secret_key'] )
    
    # 查询ip
    ret = DescribeRecord(domain,subdomain) 
    Record_dict=eval(ret.replace('null','0'))['RecordList'][0]
    # 更新解析记录
    ModifyDynamicDNS(ip,domain,Record_dict)

    



    